package com.example.springboot_mongo.controller;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.nacos.api.annotation.NacosInjected;
import com.alibaba.nacos.api.config.annotation.NacosValue;
import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.example.springboot_mongo.config.InitProcess;
import com.example.springboot_mongo.util.QrImgUtil;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.client.j2se.MatrixToImageConfig;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.sun.deploy.net.HttpResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import sun.misc.BASE64Encoder;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/")
public class TestController {

    @RequestMapping("/init")
    public Object renderInitMap() {
        return InitProcess.map;
    }


    @NacosValue(value = "${myname:null}", autoRefreshed = true)
    private String myname;

    /**
     * 下载文件
     *
     * @param request
     * @param response
     * @throws Exception
     */
    @RequestMapping("/img")
    public void downLoadImg(HttpServletRequest request, HttpServletResponse response) throws Exception {
        response.setContentType("application/octet-stream");
        response.setHeader("Content-Disposition", "attachment;filename=" + System.currentTimeMillis() + ".jpg");
        ServletOutputStream stream = response.getOutputStream();
        //读取resource下文件 resource/static/img
        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("static/img/a.jpg");
        int count = 0;
        byte[] arr = new byte[1024];
        while ((count = inputStream.read(arr)) != -1) {
            stream.write(arr, 0, count);
        }
        stream.flush();
        stream.close();
    }

    /**
     * 测试noco配置中心
     *
     * @return
     */
    @RequestMapping("/testNaco")
    public Object testNaco() {
        return myname;
    }

    @NacosInjected
    private NamingService namingService;
    @Autowired
    private RestTemplate restTemplate;

    /**
     * 测试通过
     *
     * @return
     * @throws Exception
     */
    @RequestMapping("/testRpc")
    public Object testRpc() throws Exception {
        //user 注册的服务名称
        Instance instance = namingService.selectOneHealthyInstance("user");
        if (instance != null) {
            String ip = instance.getIp();
            int port = instance.getPort();
            String url = "http://" + ip + ":" + port + "/user/init";
            ResponseEntity<JSONObject> resuult = restTemplate.getForEntity(url, JSONObject.class);
            System.out.println(resuult.getBody());
            return resuult.getBody();
        }
        return null;
    }

    @RequestMapping("/testNacos")
    public Object testNacos() throws Exception {
        //user 注册的服务名称
        Instance instance = namingService.selectOneHealthyInstance("nacos-boot");
        if (instance != null) {
            String ip = instance.getIp();
            int port = instance.getPort();
            String url = "http://" + ip + ":" + port + "/nacos/init";
            ResponseEntity<JSONObject> resuult = restTemplate.getForEntity(url, JSONObject.class);
            System.out.println(resuult.getBody());
            return resuult.getBody();
        }
        return null;
    }


    @RequestMapping("/")
    public Object testQRcode() throws Exception {
        QRCodeWriter qrCodeWriter = new QRCodeWriter();
        //第一个参数为二维码的内容 第二个参数不变  第三 四 个参数依次为 宽高
        BitMatrix bitMatrix = qrCodeWriter.encode("https://www.felord.cn", BarcodeFormat.QR_CODE, 30, 30);
        //将二维码保存为 png 本地图片。
        MatrixToImageWriter.writeToPath(bitMatrix, "png", Paths.get("D:\\workbase\\qr.png"));
        return null;
    }

    public static void main(String[] args) throws Exception {
        QRCodeWriter qrCodeWriter = new QRCodeWriter();
        Map<EncodeHintType, Object> hints = new HashMap<>();
        //纠错率
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
        //字符集
        hints.put(EncodeHintType.CHARACTER_SET,"UTF-8");
        BitMatrix bitMatrix = qrCodeWriter.encode("https://www.felord.cn", BarcodeFormat.QR_CODE, 250, 250,hints);
        MatrixToImageWriter.writeToPath(bitMatrix, "png", Paths.get("D:\\testworkspace\\qr.png"));

        //输出带logo 的二维码
        MatrixToImageConfig matrixToImageConfig = new MatrixToImageConfig(0xFF000001, 0xFFFFFFFF);
        //加入logo
        BufferedImage bufferedImage = QrImgUtil.LogoMatrix(MatrixToImageWriter.toBufferedImage(bitMatrix,matrixToImageConfig), new File("D:\\360Downloads\\a.jpg"));
        ImageIO.write(bufferedImage, "png", new File("D:\\testworkspace\\qr-logo.png"));//输出带logo图片
    }
}
